package Controller;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/CaipanSignUp")
public class CaipanSignUp extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        String sno = request.getParameter("sno");
        String sname = request.getParameter("sname");
        HttpSession session = request.getSession();
        String id = (String) session.getAttribute("id");

        try {
            Context context = new InitialContext();
            Context contextNeeded = (Context) context.lookup("java:comp/env");
            DataSource ds = (DataSource) contextNeeded.lookup("wq");// 获得连接池。
            Connection con = null;
            ResultSet rs;
            String sql;
            PreparedStatement pstmt;
            con = ds.getConnection();//获得数据源
            sql = "insert into caipan(id,sno,sname) values(?,?,?)";
            try{
                pstmt = con.prepareStatement(sql);
                pstmt.setString(1,id);
                pstmt.setString(2,sno);
                pstmt.setString(3,sname);
                pstmt.executeUpdate();
                response.getWriter().write("<script language='javascript'>alert('报名成功！');" +
                        "window.location.href='/caipan/signUp.jsp';</script>");
            }catch (SQLException e){
                response.getWriter().write("<script language='javascript'>alert('您已报名！');" +
                        "window.location.href='/caipan/signUp.jsp';</script>");
            }
            con.close();


        }catch(SQLException | NamingException e){
            System.out.println("加载不成功");
        }
    }
}
